package commonutils;

import java.util.*;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Evgeniy Krasko
 * Date: 30.10.11
 * Time: 18:46
 */
public class MyCollectionUtils {
    private static final Logger logger = Logger.getLogger(MyCollectionUtils.class.getName());

    private MyCollectionUtils() {
    }

    public static <T> List<T> asListWithoutNulls(T... elems) {
        ArrayList<T> list = new ArrayList<T>();
        for (T elem : elems) {
            if (elem != null) {
                list.add(elem);
            }
        }
        return list;
    }
    
    public static <T> List<T> asList(Collection<T> collection){
        ArrayList<T> list = new ArrayList<T>();
        for (T elem : collection) {
            list.add(elem);
        }
        return list;
    }

    public static <T> List<List<T>> splitList(List<T> list, int blockSize) {
        final List<List<T>> result = new ArrayList<List<T>>();
        int blockStart = 0;
        while (blockStart != list.size()) {
            int blockEnd = Math.min(blockStart + blockSize, list.size());
            result.add(list.subList(blockStart, blockEnd));
            blockStart = blockEnd;
        }
        return result;
    }

    public static <K, V> Map<K, V> inverseBijectiveMap(Map<V, K> originalMap) {
        final Map<K, V> result = new HashMap<K, V>();
        for (V v : originalMap.keySet()) {
            if (result.containsKey(originalMap.get(v))) {
                logger.warning("Map " + originalMap + " is not bijective");
            }
            result.put(originalMap.get(v), v);
        }
        return result;
    }

    public static <T> Set<T> asSet(Collection<T> collection) {
        final Set<T> result = new HashSet<T>();
        for (T t : collection) {
            result.add(t);
        }
        return result;
    }

}
